class Mutex {
  constructor() {
    this._locked = false;
    this._waiting = [];
  }

  lock() {
    return new Promise(resolve => {
      if (this._locked) {
        this._waiting.push(resolve);
      } else {
        this._locked = true;
        resolve();
      }
    });
  }

  unlock() {
    if (this._waiting.length > 0) {
      const resolve = this._waiting.shift();
      resolve();
    } else {
      this._locked = false;
    }
  }
}

module.exports = Mutex;